// 引入express模块
const express = require('express');
const sha1 = require('sha1');

// 引入自定义的模块\
const {url} = require('./config');
const authValidate = require('./wechat/authValidate');
const {fetchJsapiTicket} = require('./wechat/jsapiTicket');

// 创建app应用对象
const app = express();

// 配置模板资源目录，配置模板引擎
app.set('views', './views');
app.set('view engine', 'ejs');

// 页面路由
app.get('/search', async (req, res) => {
    const {ticket} = await fetchJsapiTicket();
    console.log("ticket===" + ticket);
    /*
        生成js-sdk使用签名
        1.组合参与签名的四个参数：jsapi_ticket，noncestr，timestamp，url（当前服务器地址）
        2.将其进行字典排序，以'&'拼接在一起
        3.进行sha1加密,最终输出signature
    */
    const noncestr = Math.random() + ''.split('.')[1];
    const timestamp = Date.now();
    const arr = [
        `jsapi_ticket=${ticket}`,
        `noncestr=${noncestr}`,
        `timestamp=${timestamp}`,
        `url=${url}`
    ];
    const arrStr = arr.join('&');
    const signature = sha1(arrStr);
    console.log(signature);

    // 渲染页面,将页面返回给用户
    res.render('search', {
        signature,
        noncestr,
        timestamp
    });
})


// 接收处理所有消息，监听端口号
app.use(authValidate());
app.listen(80, () => {
    console.log("服务器启动成功了...");
})

